﻿
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;

namespace RuoVea.ExCache.Cache
{
    /// <summary>
    /// 内存缓存
    /// </summary>
    public class MemoryCaches : ICache
    {
        /// <summary>
        /// 前缀
        /// </summary>
        private string _prefix = "RuoVea";
        private static MemoryCache _memoryCache = new MemoryCache(new MemoryCacheOptions());
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="prefix">缓存的前缀</param>
        public MemoryCaches(string prefix)
        {
            _prefix = prefix + ":";
        }

        #region Del
        /// <summary>
        /// 用于在 key 存在时删除 key
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>long</returns>
        public long Del(params string[] key)
        {
            foreach (var k in key)
            {
                var ke = _prefix + k;
                _memoryCache.Remove(ke);
            }
            return key.Length;
        }

        /// <summary>
        /// 用于在 key 存在时删除 key
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>long</returns>
        public Task<long> DelAsync(params string[] key)
        {
            foreach (var k in key)
            {
                var ke = _prefix + k;
                _memoryCache.Remove(ke);
            }

            return Task.FromResult((long)key.Length);
        }

        /// <summary>
        /// 用于在 key 模板存在时删除  删除带该前缀的数据
        /// </summary>
        /// <param name="pattern">pattern为前缀key: pattern* , 含有pattern的key: *pattern*</param>
        /// <returns>bool</returns>
        public async Task<long> DelByProfixAsync(string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
                return default;
            pattern = _prefix + pattern;
            var keys = GetAllKeys();
            foreach (var t in keys)
            {
                if (t.StartsWith(pattern))
                {
                    return await DelAsync(t);
                }
            }

            return default;
        }
        #endregion

        #region Exists
        /// <summary>
        /// 检查给定 key 是否存在
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>bool</returns>
        public bool Exists(string key)
        {
            return _memoryCache.TryGetValue(_prefix + key, out _);
        }

        /// <summary>
        /// 检查给定 key 是否存在
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>bool</returns>
        public Task<bool> ExistsAsync(string key)
        {
            return Task.FromResult(_memoryCache.TryGetValue(_prefix + key, out _));
        }
        #endregion

        #region Read
        /// <summary>
        /// 获取指定 key 的值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>string</returns>
        public string Read(string key)
        {
            return _memoryCache.Get(_prefix + key)?.ToString();
        }

        /// <summary>
        /// 获取指定 key 的值
        /// </summary>
        /// <typeparam name="T">byte[] 或其他类型</typeparam>
        /// <param name="key">键</param>
        /// <returns>T</returns>
        public T Read<T>(string key)
        {
            return _memoryCache.Get<T>(_prefix + key);
        }

        /// <summary>
        /// 获取指定 key 的值
        /// </summary>
        /// <param name="key">键</param>
        /// <returns>string</returns>
        public Task<string> ReadAsync(string key)
        {
            return Task.FromResult(Read(key));
        }

        /// <summary>
        /// 获取指定 key 的值
        /// </summary>
        /// <typeparam name="T">byte[] 或其他类型</typeparam>
        /// <param name="key">键</param>
        /// <returns>T</returns>
        public Task<T> ReadAsync<T>(string key)
        {
            return Task.FromResult(Read<T>(key));
        }
        #endregion

        #region Write
        /// <summary>
        /// 设置指定 key 的值，所有写入参数object都支持string | byte[] | 数值 | 对象
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>bool</returns>
        public bool Write(string key, object value)
        {
            key = _prefix + key;
            _memoryCache.Set(key, value);
            return true;
        }

        /// <summary>
        /// 设置指定 key 的值，所有写入参数object都支持string | byte[] | 数值 | 对象
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expire">有效期</param>
        /// <returns>bool</returns>
        public bool Write(string key, object value, TimeSpan expire)
        {
            key = _prefix + key;
            _memoryCache.Set(key, value, expire);
            return true;
        }

        /// <summary>
        /// 设置指定 key 的值，所有写入参数object都支持string | byte[] | 数值 | 对象
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <returns>bool</returns>
        public Task<bool> WriteAsync(string key, object value)
        {
            Write(key, value);
            return Task.FromResult(true);
        }

        /// <summary>
        /// 设置指定 key 的值，所有写入参数object都支持string | byte[] | 数值 | 对象
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expire">有效期</param>
        /// <returns>bool</returns>
        public Task<bool> WriteAsync(string key, object value, TimeSpan expire)
        {
            Write(key, value, expire);
            return Task.FromResult(true);
        }
        #endregion

        #region 获取所有的键值
        /// <summary>
        /// 获取所有的键值
        /// </summary>
        /// <returns>string</returns>
        private List<string> GetAllKeys()
        {
            const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
            var entries = _memoryCache.GetType().GetField("_entries", flags).GetValue(_memoryCache);
            var cacheItems = entries as IDictionary;
            var keys = new List<string>();
            if (cacheItems == null) return keys;
            foreach (DictionaryEntry cacheItem in cacheItems)
            {
                keys.Add(cacheItem.Key.ToString());
            }
            return keys;
        } 
        #endregion

        /// <summary>
        /// 从缓存里取数据，如果不存在则执行查询方法，
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="key">键值</param>
        /// <param name="GetFun">查询方法</param>
        /// <param name="timeSpanMin">有效期 单位分钟/param>
        /// <returns></returns>
        public T Cof_ReadWrite<T>(string key, Func<T> GetFun, TimeSpan timeSpanMin) where T : class
        {
            var obj = Read<T>(key);
            obj = GetFun();
            if (obj == null)
            {
                obj = GetFun();
                Write(key, obj, timeSpanMin);
            }

            return obj as T;
        }
    }
}